package cn.ysym.tcsy;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.ysym.dao.SettingDao;
import cn.ysym.model.GeneralBean;
import cn.ysym.model.Setting;
import cn.ysym.util.CommonUtil;
import cn.ysym.util.HttpUtil;
import cn.ysym.util.VibratorUtil;

public class UpdateActivity extends AppCompatActivity {

    @BindView(R.id.lvData)
    ListView lvData;
    @BindView(R.id.bSubmit)
    Button bSubmit;
    @BindView(R.id.bEdit)
    Button bEdit;
    @BindView(R.id.bCancel)
    Button bCancel;
    @BindView(R.id.progressBarOnline)
    ProgressBar progressBar;
    private SettingDao settingDao;
    private UpDataTask upDataTask;
    private UpAllDataTask upAllDataTask;
    private List erpList;
    private String shippingId;
    private List<HashMap<String, Object>> listData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update);
        ButterKnife.bind(this); //绑定butterKnife插件
        setTitle("修改出库");
        settingDao = new SettingDao(this);
        initData();

        bSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //提交出库完成
                progressBar.setVisibility(View.VISIBLE);
                ShippingFinishTask task = new ShippingFinishTask(shippingId);
                task.execute((Void) null);
            }
        });

        bEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //弹出退出确认框
                new AlertDialog.Builder(UpdateActivity.this)
                        .setTitle("系统提示")
                        .setMessage("确认修改吗？")
                        .setPositiveButton("确认", new android.content.DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //更新数量
                                upAllDataTask = new UpAllDataTask(shippingId);
                                upAllDataTask.execute((Void) null);

                            }
                        }).setNegativeButton("取消", null).show();
            }
        });

        bCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

    }

    private void updateNum() {
        //设置成功数量
        for (HashMap map : listData) {
            map.put("sentNum", String.valueOf(map.get("sendNum")));
        }
        SimpleAdapter adapter = new SimpleAdapter(UpdateActivity.this, listData, R.layout.shipping_data_item,
                new String[]{"productId", "productName", "sendNum", "sentNum"}, new int[]{R.id.tvProductId, R.id.tvProductName, R.id.tvSendNum, R.id.tvSentNum});
        lvData.setAdapter(adapter);

    }

    private void initData() {
        Intent intent = getIntent();
        ArrayList<GeneralBean> generalBeans = (ArrayList<GeneralBean>) intent.getSerializableExtra("general");
        shippingId = intent.getStringExtra("shippingId");
        listData = new ArrayList<>();
        erpList = new ArrayList();
        for (int i = 0; i < generalBeans.size(); i++) {
            HashMap<String, Object> oneData = new HashMap<>();
            String productId = generalBeans.get(i).getProductId();
            String productName = generalBeans.get(i).getProductName();
            String sendNum = generalBeans.get(i).getSendNum();
            String sentNum = generalBeans.get(i).getSentNum();
            oneData.put("productId", productId);
            erpList.add(productId);
            oneData.put("productName", productName);
            oneData.put("sendNum", sendNum);
            oneData.put("sentNum", sentNum);
            listData.add(oneData);
        }
        SimpleAdapter adapter = new SimpleAdapter(UpdateActivity.this, listData, R.layout.shipping_data_item,
                new String[]{"productId", "productName", "sendNum", "sentNum"}, new int[]{R.id.tvProductId, R.id.tvProductName, R.id.tvSendNum, R.id.tvSentNum});
        lvData.setAdapter(adapter);
    }

    public class UpAllDataTask extends AsyncTask<Void, Void, String> {
        private String shippingId;

        public UpAllDataTask(String shippingId) {
            this.shippingId = shippingId;
        }

        @Override
        protected String doInBackground(Void... params) {
            JSONObject req = new JSONObject();
            try {
                Setting userName = settingDao.query("userName");
                Setting sessionKey = settingDao.query("sessionKey");
                req.put("version", "2.3.180801.a.main");
                req.put("account", userName.getSettingValue());
                req.put("shippingId", shippingId);
                req.put("erpList", erpList);
                req.put("sign", HttpUtil.genSign(req, sessionKey.getSettingValue()));
                String retStr = HttpUtil.postJson("updateAllShipping.sdo", req.toString());
                return retStr;
            } catch (Exception e) {
                Log.d("zqfw", e.getMessage());
            }
            return null;
        }

        @Override
        protected void onPostExecute(final String retStr) {
            upDataTask = null;
            progressBar.setVisibility(View.GONE);

            if (retStr != null) {
                try {
                    JSONObject retJson = new JSONObject(retStr);
                    if (retJson.getInt("status") == 200) {
                        Toast.makeText(getApplicationContext(), "成功", Toast.LENGTH_SHORT).show();
                        updateNum();
                        bSubmit.setEnabled(true);
                        bEdit.setEnabled(false);

                    } else {
                        VibratorUtil.vibrate(UpdateActivity.this, VibratorUtil.pattern, false);
                        Toast.makeText(getApplicationContext(), retJson.getString("msg"), Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    Log.d("zqfw", e.getMessage());
                }

            } else {
                VibratorUtil.vibrate(UpdateActivity.this, VibratorUtil.pattern, false);
                Toast.makeText(getApplicationContext(), "失败：内部错误，请稍后重试", Toast.LENGTH_SHORT).show();
            }

        }

    }

    public class UpDataTask extends AsyncTask<Void, Void, String> {
        private int shippingLogId;
        private int addProductNum;
        private String productId;

        public UpDataTask(int shippingLogId, int addProductNum, String productId) {
            this.shippingLogId = shippingLogId;
            this.addProductNum = addProductNum;
            this.productId = productId;
        }

        @Override
        protected String doInBackground(Void... params) {
            JSONObject req = new JSONObject();
            try {
                Setting userName = settingDao.query("userName");
                Setting sessionKey = settingDao.query("sessionKey");
                req.put("version", "2.3.180801.a.main");
                req.put("account", userName.getSettingValue());
                req.put("shippingLogId", shippingLogId);
                req.put("productId", productId);
                req.put("productNum", addProductNum);
                req.put("sign", HttpUtil.genSign(req, sessionKey.getSettingValue()));
                String retStr = HttpUtil.postJson("updateShipping.sdo", req.toString());
                return retStr;
            } catch (Exception e) {
                Log.d("zqfw", e.getMessage());
            }
            return null;
        }

        @Override
        protected void onPostExecute(final String retStr) {
            upDataTask = null;
            progressBar.setVisibility(View.GONE);

            if (retStr != null) {
                try {
                    JSONObject retJson = new JSONObject(retStr);
                    if (retJson.getInt("status") == 200) {
                        Toast.makeText(getApplicationContext(), "成功", Toast.LENGTH_SHORT).show();
                        updateNum();

                    } else {
                        VibratorUtil.vibrate(UpdateActivity.this, VibratorUtil.pattern, false);
                        Toast.makeText(getApplicationContext(), retJson.getString("msg"), Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    Log.d("zqfw", e.getMessage());
                }

            } else {
                VibratorUtil.vibrate(UpdateActivity.this, VibratorUtil.pattern, false);
                Toast.makeText(getApplicationContext(), "失败：内部错误，请稍后重试", Toast.LENGTH_SHORT).show();
            }

        }

    }

    public class ShippingFinishTask extends AsyncTask<Void, Void, String> {
        private String shippingId;
        private String message = "对不起，服务异常！";

        public ShippingFinishTask(String shippingId) {
            this.shippingId = shippingId;
        }

        @Override
        protected String doInBackground(Void... params) {
            JSONObject req = new JSONObject();
            try {
                Setting userName = settingDao.query("userName");
                Setting sessionKey = settingDao.query("sessionKey");

                req.put("version", CommonUtil.getSoftVersion());
                req.put("account", userName.getSettingValue());
                req.put("billCode", shippingId);
                req.put("sign", HttpUtil.genSign(req, sessionKey.getSettingValue()));
                String retStr = HttpUtil.postJson("syncShippingDataToErp.sdo", req.toString());
                return retStr;
            } catch (Exception e) {
                message = e.getMessage();
            }

            return null;
        }

        @Override
        protected void onPostExecute(final String retStr) {
            progressBar.setVisibility(View.GONE);

            if (retStr != null) {
                try {
                    JSONObject retJson = new JSONObject(retStr);
                    message = retJson.getString("message");
                    if (retJson.getInt("result") == 1) bSubmit.setEnabled(false);
                } catch (JSONException e) {
                    message = e.getMessage();
                }

            }
            VibratorUtil.vibrate(getApplicationContext(), VibratorUtil.milliSeconds);
            Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
        }

    }

}